package cn.hairui.fastms.base.config;

import cn.hairui.fastms.constant.GlobalConstant;
import cn.hairui.fastms.core.bean.SUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * <h2>默认拦截器</h2>
 *  <ol>判断用户是否登录，非登录用户需要跳先登录系统后才能使用</ol>
 * <h2>修改历史</h2>
 *  <ol>如有修改，请添加修改历史</ol>
 * </p>
 *
 * @author lihairui
 * @date 2020/11/11 16:42
 * @copyright 李海瑞
 */
@Component
public class DefaultInterceptor implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(GlobalConstant.LOG_SYSTEM);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        SUser sUser = (SUser) request.getSession().getAttribute(GlobalConstant.GLOBAL_SESSION_NAME);
        if (sUser == null) {
            //logger.info("USER           : {}", "");
            response.sendRedirect("/login");
            return false;
        }
        //logger.info("USER           : {}", sUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        //controller方法处理完毕后，调用此方法
        //logger.info("在后端控制器执行后调用 ");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //页面渲染完毕后调用此方法
        //logger.info("整个请求执行完成后调用 ");
    }

}
